# -*- coding: utf-8 -*-

import sys
import threading
from PyQt5.QtCore import QUrl,QThread,pyqtSignal
from PyQt5.QtWidgets import QApplication,QMainWindow,QCheckBox
from FFXIViterableSearch import iterableSearch
from FFXIVfirstSearch import firstSearch
from FFXIVKeySearch import keySearch
from UI_FFXIVItemSearch import Ui_MainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView
from bs4 import BeautifulSoup
import time


class MainWindow(QMainWindow,Ui_MainWindow):

    def __init__(self, parent = None):
        super(MainWindow,self).__init__(parent)
        self.setupUi(self)
        self.button_SearchSure.clicked.connect(self.search)
        self.button_refresh.clicked.connect(self.refresh)#删掉
        self.label_wiki.linkActivated.connect(self.openWeb)
        self.list_keySearchResult.doubleClicked.connect(self.listClicked)
        self.searchMode.setChecked(True)
        self.countMode.setChecked(False)
        self.label_wiki.setOpenExternalLinks(False)
        self.label_wiki.setText("<A href='https://ff14.huijiwiki.com/wiki/ItemSearch'>灰机WIKI物品检索</a>")
        # ----------子线程交互-----------#
        self.keySearchWork=keySearchTread()
        self.keySearchWork.label_newsL_signal.connect(self.__label_newsL_set)
        self.keySearchWork.list_keySearchResult_signal.connect(self.__list_keySearchResult_set)
        self.searchWork=searchTread()
        self.searchWork.label_newsR_signal.connect(self.__label_newsR_set)
        self.searchWork.label_newsL_signal.connect(self.__label_newsL_set)
        self.searchWork.text_outPutResult_signal.connect(self.__text_outPutResult_set)
        self.searchWork.lable_usingTime_signal.connect(self.__lable_usingTime_set)
        self.searchWork.text_outPutResult_clear_signal.connect(self.clearOutText)
        self.searchWork.list_keySearchResult_signal.connect(self.__list_keySearchResult_set)


    def __label_newsL_set(self,string):
        self.label_newsL.setText(string)

    def __list_keySearchResult_set(self,alist):
        self.list_keySearchResult.addItems(alist)

    def __label_newsR_set(self,string):
        self.label_newsR.setText(string)

    def __text_outPutResult_set(self,string):
        self.text_outPutResult.append(string)

    def __lable_usingTime_set(self,string):
        self.lable_usingTime.setText(string)


    def listClicked(self,item):
        if self.keySearchWork.get_Running()==False and self.searchWork.get_Running()==False:
            item=self.list_keySearchResult.item(item.row()).text()
            if item.find('×') > 0:
                item=item[0:item.find('×')]
            self.search(item)
        else: return

            #将信息发送到主线程，触发信号槽
    def search(self,fromList=None): 
        if fromList==False:
            changeList=True
            item=self.text_inPutItemName.text()
            self.list_keySearchResult.clear()
        else: 
            item=fromList
            changeList=False
        if (self.searchMode.isChecked()) and bool(fromList)==False and item!='':
            self.label_newsL.setText('贽殿纱那翻阅中…')
            self.label_wiki.setText("<A href='https://ff14.huijiwiki.com/wiki/ItemSearch?name="+item+"'>WIKI：关键词["+item+"]结果页</a>")
            thread=threading.Thread(target=self.keySearchWork.run,args=(item,))
            thread.start()
        else:
            if self.countMode.isChecked():
                existingResult=self.text_outPutResult.toPlainText()
                existingResultList=[]
                tempStr=''
                for each in existingResult:
                    if each == '\n':
                        existingResultList.append(tempStr)
                        tempStr=''
                    else:
                        tempStr=tempStr+each
                existingResultList.append(tempStr)
            else: existingResultList=[]
            self.label_newsR.setText("%s 检索中…"%item)
            self.label_wiki.setText("<A href='https://ff14.huijiwiki.com/wiki/物品:"+item+"'>WIKI："+item+"</a>")
            thread=threading.Thread(target=self.searchWork.run,args=(item,changeList,existingResultList,self.countMode.isChecked(),))
            thread.start()
         


    def refresh(self):
        temp=self.text_outPutResult.toPlainText()
        self.text_outPutResult.clear()
        self.text_outPutResult.append(temp)
        return

    def openWeb(self):
        url=BeautifulSoup(self.label_wiki.text())
        self.text_web=QWebEngineView()
        self.text_web.setWindowTitle('Wiki')
        self.text_web.load(QUrl(url.a.get('href')))
        self.text_web.show()

    def clearOutText(self):
        self.text_outPutResult.clear()

class searchTread(QThread):
    label_newsR_signal=pyqtSignal(str)
    label_newsL_signal=pyqtSignal(str)
    text_outPutResult_signal=pyqtSignal(str)
    lable_usingTime_signal=pyqtSignal(str)
    text_outPutResult_clear_signal=pyqtSignal()
    list_keySearchResult_signal=pyqtSignal(list)
    def __init__(self, *args, **kwargs):
        self._Running=False
        return super().__init__(*args, **kwargs)

    def run(self,item,changeList=True,existingResult=[],countMode=False):
        self._Running=True
        startTime=time.time()
        result=fSearch.work(item)#first search
        #mainWindow.text_outPutResult.clear()
        if len(result)==1:
            if len(existingResult)<=1:
                self.text_outPutResult_clear_signal.emit()
                self.text_outPutResult_signal.emit('未查询到"'+ item +'"的配方，应该是不可制作物品。')
            self.label_newsR_signal.emit('莱斯利感到莫名其妙')
            if changeList==True:
                self.label_newsL_signal.emit('贽殿纱那找到了这些')
                self.list_keySearchResult_signal.emit(result['产量'][1])
        else:

            if changeList==True:
                list1=list(result.keys())
                for name in list1[1:]:
                    tempX=list1.index(name)
                    list1[tempX]=list1[tempX]+' ×'
                    for i in range(len(result[name])):
                        list1[tempX]=list1[tempX]+result[name][i]+' '
                self.label_newsL_signal.emit('贽殿纱那找到了这些')
                self.list_keySearchResult_signal.emit(list1[1:])
                self.list_keySearchResult_signal.emit(result['产量'][1])
            iterReasult=iSearch.work(result)
            existingItemName=[]
            existingItemNum=[]
            if countMode and len(existingResult)>1 :
                tempItem=item+' + '+existingResult[0]
                for each in existingResult[1:]:
                    existingItemName.append(each[0:each.find("×")])
                    existingItemNum.append(each[each.find("×")+1:])
                for each in existingItemName:
                    itemInDict=iterReasult.get(each,['0'])
                    itemInDict[0]=str(int(itemInDict[0])+int(existingItemNum[existingItemName.index(each)]))
                    iterReasult[each]=list(itemInDict)
            else: tempItem=item
            self.text_outPutResult_clear_signal.emit()
            self.text_outPutResult_signal.emit(str(iterReasult['产量'][0])+"×"+tempItem)

            del iterReasult['产量']
            for Name, Value in iterReasult.items():
                temp = str(Name)+"×"+str(Value[0])
                self.text_outPutResult_signal.emit(temp)
                #mainWindow.text_outPutResult.append(temp)
            time.sleep(0.1)
            self.label_newsR_signal.emit("检索成功:%s"%item)
        endTime=time.time()
        usingTime=endTime-startTime
        self.lable_usingTime_signal.emit('检索用时：%s'%int(usingTime+1)+'秒')
        self._Running=False

    def get_Running(self):
        return self._Running

class keySearchTread(QThread):
    label_newsL_signal=pyqtSignal(str)
    list_keySearchResult_signal=pyqtSignal(list)
    def __init__(self, *args, **kwargs):
        self._Running=False
        return super().__init__(*args, **kwargs)
    def run(self,item):
        self._Running=True
        result=kSearch.work(item)
        self.label_newsL_signal.emit(result[0][1:-4]+',显示 '+str(len(result)-1)+' 个.')
        self.list_keySearchResult_signal.emit(result[1:])
        self._Running=False
    def get_Running(self):
        return self._Running



if __name__ == "__main__":
    app=QApplication(sys.argv)
    fSearch=firstSearch()
    iSearch=iterableSearch()
    kSearch=keySearch()
    mainWindow=MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())